package top.huntwolf.admin.interceptor;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.huntwolf.admin.common.enums.CodeMsg;
import top.huntwolf.admin.exception.ServiceException;
import top.huntwolf.admin.pojo.shop.ShopContext;
import top.huntwolf.admin.service.ShopService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StoreInterceptor implements HandlerInterceptor {

    @Autowired
    private ShopService shopService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String store = request.getHeader("yqm-store");

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (store == null){
            return true;
        }
        int storeId = 0;
        try {
            storeId = Integer.parseInt(store);
        }catch (Exception e){
            throw new ServiceException(CodeMsg.YQM_STORE_ERROR.fillArgs("storeId错误"));
        }
        if(shopService.searchBookShopById(storeId) == null){
            throw new ServiceException(CodeMsg.YQM_STORE_ERROR.fillArgs("暂无此店"));
        }
        //设置分店id
        ShopContext.set(storeId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ShopContext.remove();
    }
}
